package org.example.elm_xiangmu.service.impl;

import org.example.elm_xiangmu.mapper.UserMapper;
import org.example.elm_xiangmu.po.User;
import org.example.elm_xiangmu.result.Result;
import org.example.elm_xiangmu.service.UserService;
import org.example.elm_xiangmu.utils.JwtUtil;
import org.example.elm_xiangmu.utils.LoginResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public Result getUserByIdByPass(String userId, String password) {

      User user =  userMapper.getUserByIdByPass(userId);
      if (user == null) {
          return Result.error("用户ID不存在");
      } else if (user.getPassword().equals(password)) {
          //登陆成功
          Map<String,Object> claims = new HashMap<>();
          claims.put("userId",user.getUserId());
          claims.put("password",user.getPassword());
          String token = JwtUtil.genToken(claims);
          LoginResponse loginResponse = new LoginResponse();
          loginResponse.setToken(token);
          loginResponse.setData(user);
          return Result.success(loginResponse,"查询用户信息成功");
      }
      return Result.error("ID或密码错误");
    }

    @Override
    public Result getUserById(String userId) {
        Integer a = userMapper.getUserById(userId);
        return Result.success(a);
    }

    @Override
    public Result saveUser(User user) {
        Integer a = userMapper.saveUser(user);
        if(a == 1){
            return Result.success(a,"注册成功");
        }
        return Result.error("注册失败");
    }
}
